package com.powerunion.datacollection.service;

import java.util.Date;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.Format;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.CollectionTaskInstanceDao;
import com.powerunion.datacollection.dao.DaoFactory;
import com.powerunion.datacollection.model.CollectionTaskInstance;
import com.powerunion.datacollection.model.ItemInfo;
import com.powerunion.datacollection.model.jsonObject.CollectionTaskInstanceJO;
import com.powerunion.datacollection.workflow.domain.TaskInstance;
import com.powerunion.util.log.LogHelper;

public class CollectionTaskInstanceManager {
	private static Logger logger = LogHelper.getInstance().getLogger(
			CollectionTaskInstanceManager.class);
	private CollectionTaskInstanceDao dao = null;

	public CollectionTaskInstanceManager() {
		super();
		this.dao = (CollectionTaskInstanceDao) DaoFactory.getInstance().getDao(
				CollectionTaskInstanceDao.class);
	}

	public String save(String saveStr, String currentUser) throws Exception {
		// 参数为空
		if (StringUtils.isEmpty(saveStr)) {
			String[] args = { "saveStr" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter saveStr NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		JSONObject jsonObject = JSONObject.fromObject(saveStr);
		CollectionTaskInstanceJO ctjo = (CollectionTaskInstanceJO) JSONObject
				.toBean(jsonObject, CollectionTaskInstanceJO.class);
		TaskInstance ck = new TaskInstance();

		//复制属性值
		BeanUtils.copyProperties(ck, ctjo);

		ck.setCreateDate(new Date());
		String createDate = Format.getInstance().dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");

		ck.setCrtUserCode(currentUser);

		ProcessInfoManager pm = new ProcessInfoManager();
		String validateStr = pm.validateActivityInfo(ck.getProcId());
		if (StringUtils.isEmpty(validateStr)) {
			String itemInfo = ck.getProcItemInfo();
			String proInfo = ck.getProcActInfo();
			String itemId = "";
			ProcessInstanceManager pim = new ProcessInstanceManager();
			ItemManager itm = new ItemManager();
			//查找该任务实例是否已经绑定流程实例信息
			ItemInfo itfo = itm
					.findByKey(ck.getProcId(), Constants.PROINSTANCE);
			if (StringUtils.isEmpty(itemInfo) && StringUtils.isEmpty(proInfo)) {//流程信息为空
				if (StringUtils.isEmpty(itfo.getId())) {//为空则说明还没有绑定流程实例信息，则从流程定义信息拷贝一份数据生成流程实例信息
					itemId = pim.copyProcInfo(ck.getProcId(), currentUser,createDate);
				} else {
					itemId = itfo.getId();
				}
			} else {//非空则说明用户在前台修改了流程信息
				if (StringUtils.isEmpty(itfo.getId())) {//流程实例为空，则说明是第一次创建任务实例修改的是流程定义信息而非是修改任务实例中的流程实例信息
					itemId = pim.save(proInfo, currentUser, itemInfo, ck
							.getProcId(),createDate);
				} else {//流程实例非空，则说明修改的是任务实例中的流程实例
					String proDefineID = pim.getProcDefineId(itfo.getId());
					//得到保存后的流程实例的id
					itemId = pim.save(proInfo, currentUser, itemInfo,
							proDefineID,createDate);
				}

			}

			if (StringUtils.isEmpty(itemId)) {
				return "";
			} else {
				//设置保存后的流程实例id的值
				ck.setProcId(itemId);
				String[] codes = new String[1];
				codes[0] = ck.getId();
				this.dao.delete(codes);

				TaskInstance collectionTaskInstance = this.dao
						.save(ck);
				if (collectionTaskInstance != null) {
					boolean flag = pim.initSubmissionWorkItems(
							collectionTaskInstance.getProcId(),
							collectionTaskInstance.getFormId());
					if (flag) {
						//更新任务实例的状态
						this.dao.updateTaskInstanceState(collectionTaskInstance
								.getId(), 1);
						//更新任务信息定义表中的任务实例个数字段
						CollectionTaskManager ctm = new CollectionTaskManager();
						ctm.updateTaskInstanceNum(collectionTaskInstance
								.getTaskDefineId());
						return "";
					} else {
						return "生成报送任务失败！";
					}
				} else {
					return "保存任务实例失败！";
				}
			}

		} else {
			return validateStr;
		}

	}

	public boolean delete(String[] codes) throws Exception {
		//参数为空
		if (codes.length < 1) {
			String[] args = { "codes" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter codes NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		return this.dao.delete(codes);
	}

	public CollectionTaskInstance findByKey(String id) throws Exception {
		//参数为空
		if (StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		return this.dao.getBykey(id);
	}

	public String getCollectionTaskInstances(int start, int limit,
			String userCode) {
		//参数为空
		if (StringUtils.isEmpty(userCode)) {
			String[] args = { "userCode" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter userCode NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.getCollectionTaskInstances(start, limit, userCode);
	}

	/**
	 * 暂停任务
	 * @param procId 流程实例id
	 * @param taskId 任务实例id
	 * @return
	 * @throws Exception
	 */
	public boolean suspendTask(String procId, String taskId) throws Exception {
		//参数为空
		if (StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		//参数为空
		if (StringUtils.isEmpty(taskId)) {
			String[] args = { "taskId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter taskId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		ApproveWorkItemManager aim = new ApproveWorkItemManager();
		aim.suspendApproveWork(procId);
		SubmissionWorkItemManager swi = new SubmissionWorkItemManager();
		swi.suspendSubmissionWork(procId);

		return this.dao.updateTaskInstanceState(taskId, Constants.TASK_SUSPEND);
	}

	public boolean resumeTask(String procId, String taskId) throws Exception {
		//参数为空
		if (StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		//参数为空
		if (StringUtils.isEmpty(taskId)) {
			String[] args = { "taskId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter taskId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		ApproveWorkItemManager aim = new ApproveWorkItemManager();
		aim.resumeApproveWork(procId);
		SubmissionWorkItemManager swi = new SubmissionWorkItemManager();
		swi.resumeSubmissionWork(procId);

		return this.dao
				.updateTaskInstanceState(taskId, Constants.TASK_IN_ROUGH);
	}

	public boolean updateTaskInstanceState(String id, int state)
			throws Exception {
		//参数为空
		if (StringUtils.isEmpty(id)) {
			String[] args = { "id" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter id NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		return this.dao.updateTaskInstanceState(id, state);
	}

	public boolean updateTaskInstanceStateByProc(String procId, int state)
			throws Exception {
		//参数为空
		if (StringUtils.isEmpty(procId)) {
			String[] args = { "procId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter procId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}

		return this.dao.updateTaskInstanceStateByProc(procId, state);
	}

	/**
	 * 启动任务
	 * @param saveStr
	 * @param currentUser
	 * @return
	 * @throws Exception
	 */
	public String startupTask(String saveStr, String currentUser)
			throws Exception {
		//参数为空
		if (StringUtils.isEmpty(saveStr)) {
			String[] args = { "saveStr" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter saveStr NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		//参数为空
		if (StringUtils.isEmpty(currentUser)) {
			String[] args = { "currentUser" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter currentUser NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
//TaskScheduler.getInstance().scheduleMinutely(Task.class, "Test", 1, 4);
//TaskScheduler.getInstance().scheduleSecondly(Task.class, "测试启动任务", 5, 3);
//return "success"; 
//		JobDetail jd = new JobDetail();
//		jd.getJobDataMap().put("urgenContent", "测试启动。。。。。");
//		jd.getJobDataMap().put("userCode", "ldz");
//		jd.getJobDataMap().put("id", "55555");
//		jd.getJobDataMap().put("type", String.valueOf(Constants.TASK_TYPE_SUBMISSIONWORK));
////		
//		StringBuffer taskName = new StringBuffer();
//		taskName.append("55555").append("_sw_urgen");
////		String cronTime = "0 0,15,30,45 * * * ?";
////		//TaskScheduler.getInstance().schedule(UrgencyTask.class, taskName.toString(), cronTime,jd);
//		//TaskScheduler.getInstance().scheduleSecondly(Task.class, taskName.toString(), 3, 5, jd);
//		//TaskScheduler.getInstance().start();
//		//TaskScheduler.getInstance().scheduleMinutely(Task.class, taskName.toString(), 1, 3);
////		
//		
//		JobDetail jobDetail = new JobDetail("job1_1","jGroup1", Task.class);
//
//		SimpleTrigger simpleTrigger = new SimpleTrigger("trigger1_1","tgroup1");
//
//		simpleTrigger.setStartTime(new Date());
//
//		simpleTrigger.setRepeatInterval(2000);
//
//		simpleTrigger.setRepeatCount(5);
//
//		SchedulerFactory schedulerFactory = new StdSchedulerFactory();
//
//		Scheduler scheduler = schedulerFactory.getScheduler();
//
//		scheduler.scheduleJob(jobDetail, simpleTrigger);
//
//		scheduler.start();
//
//
//		
//		return "";
//		

		JSONObject jsonObject = JSONObject.fromObject(saveStr);
		CollectionTaskInstanceJO ctjo = (CollectionTaskInstanceJO) JSONObject
				.toBean(jsonObject, CollectionTaskInstanceJO.class);
		TaskInstance ck = new TaskInstance();

		//复制属性值
		BeanUtils.copyProperties(ck, ctjo);

		ck.setCreateDate(new Date());
		String createDate = Format.getInstance().dateToString(new Date(), "yyyy-MM-dd HH:mm:ss");

		ck.setCrtUserCode(currentUser);

		//得到流程的定义信息
		String proInfo = ck.getProcActInfo();
		String validateStr = "";
		/**
		 * 虽然前台启动任务的时候已经通过ProcessInfoManager的validateActivityInfo方法检测
		 * 流程的完整性，但这里为了以防万一还是判断检测一下
		 */
		ProcessInstanceManager pim = new ProcessInstanceManager();
		String itemId = "";
		if (StringUtils.isEmpty(proInfo)) {//流程信息为空就检测一下是否完整
			ProcessInfoManager pm = new ProcessInfoManager();
			//检查流程信息是否完整
			validateStr = pm.validateActivityInfo(ck.getProcId());
			if (StringUtils.isEmpty(validateStr)) {
				//如果流程信息为空，则说明用户没有修改任何的流程信息，说明流程信息是完整的，则直接复制流程定义信息生成流程实例
				//得到保存后的流程实例的id
				itemId = pim.copyProcInfo(ck.getProcId(), currentUser,createDate);
			} else {
				return validateStr;
			}
		} else {//非空，则说明用户已经修改了流程信息
			ItemManager im = new ItemManager();
			ItemInfo itemInfo = im.findByKey(ck.getProcId());
			itemInfo.setItemType(Constants.PROINSTANCE);
			itemInfo.setId("");
			//得到保存后的流程实例的id 
			itemId = pim.save(proInfo, currentUser, itemInfo, ck.getProcId(),createDate);
		}

		if (StringUtils.isEmpty(itemId)) {
			return "保存任务实例失败！";
		} else {
			//设置保存后的流程实例id的值
			ck.setProcId(itemId);
			String[] codes = new String[1];
			codes[0] = ck.getId();
			//先删除原有的记录 假如存在的话
			this.dao.delete(codes);

			TaskInstance collectionTaskInstance = this.dao.save(ck);
			if (collectionTaskInstance != null) {
				boolean flag = pim.initSubmissionWorkItems(
						collectionTaskInstance.getProcId(),
						collectionTaskInstance.getFormId());
				if (flag) {
					//更新任务信息定义表中的任务实例个数字段
//					CollectionTaskManager ctm = new CollectionTaskManager();
//					ctm.updateTaskInstanceNum(collectionTaskInstance
//							.getTaskDefineId());
					
					
					return "success";
				} else {
					return "生成报送任务失败！";
				}
			} else {
				return "保存任务实例失败！";
			}

		}

	}
	
	public TaskInstance save(TaskInstance ct) throws Exception {
		//参数为空
		if (ct == null) {
			String[] args = { "ct" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter ct NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}
		
		return this.dao.save(ct);
	}

}
